<template>
  <div class="outsourcing-management">
    <div class="page-header">
      <h2>外发加工管理</h2>
      <el-button type="primary" @click="handleShowCreateDialog">
        <el-icon><Plus /></el-icon>
        新增外发单
      </el-button>
    </div>

    <!-- 查询条件 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline size="default">
        <el-form-item label="外发单号">
          <el-input
            v-model="searchForm.outsourcingNo"
            placeholder="请输入外发单号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="供应商代码">
          <el-input
            v-model="searchForm.supplierCode"
            placeholder="请输入供应商代码"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="供应商名称">
          <el-input
            v-model="searchForm.supplierName"
            placeholder="请输入供应商名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="产品名称">
          <el-input
            v-model="searchForm.productName"
            placeholder="请输入产品名称"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="已外发" value="已外发" />
            <el-option label="加工中" value="加工中" />
            <el-option label="已回厂" value="已回厂" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="外发日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="报价单号">
          <el-input
            v-model="searchForm.quotationNo"
            placeholder="请输入报价单号"
            clearable
            style="width: 180px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 外发单列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="outsourcingNo" label="外发单号" width="150" fixed="left" />
        <el-table-column prop="quotationNo" label="报价单号" width="150" />
        <el-table-column prop="supplierCode" label="供应商代码" width="120" />
        <el-table-column prop="supplierName" label="供应商名称" width="180" />
        <el-table-column prop="productName" label="产品名称" width="150" />
        <el-table-column prop="materialCode" label="物料编码" width="120" />
        <el-table-column prop="quantity" label="外发数量" width="100" align="right" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="外发单价" width="100" align="right">
          <template #default="{ row }">
            <span>{{ formatCurrency(row.unitPrice) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="totalAmount" label="外发总金额" width="120" align="right">
          <template #default="{ row }">
            <span>{{ formatCurrency(row.totalAmount) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outsourcingDate" label="外发日期" width="120" />
        <el-table-column prop="expectedReturnDate" label="预计回厂日期" width="130" />
        <el-table-column prop="actualReturnDate" label="实际回厂日期" width="130" />
        <el-table-column prop="createdBy" label="创建人" width="100" />
        <el-table-column prop="createdAt" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewDetail(row)">详情</el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleUpdateStatus(row)"
              :disabled="row.status === '已回厂' || row.status === '已取消'"
            >
              更新状态
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleDelete(row)"
              :disabled="row.status === '已回厂'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增外发单对话框 -->
    <el-dialog
      v-model="showCreateDialog"
      title="新增外发单"
      width="1200px"
      :before-close="handleCreateDialogClose"
    >
      <div v-if="!selectedQuotation" class="quotation-selection">
        <h4>第一步：选择报价记录</h4>
        <el-table
          v-loading="quotationLoading"
          :data="availableQuotations"
          border
          style="width: 100%; margin-top: 10px;"
          :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
          @row-click="handleQuotationSelect"
          row-class-name="clickable-row"
        >
          <el-table-column prop="quotationNo" label="报价单号" width="150" />
          <el-table-column prop="customerName" label="客户名称" width="180" />
          <el-table-column prop="salesperson" label="业务员" width="120" />
          <el-table-column prop="orderDate" label="订单日期" width="120" />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="getQuotationStatusTagType(row.status)">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="totalAmount" label="总金额" width="120" align="right">
            <template #default="{ row }">
              <span>{{ formatCurrency(row.totalAmount) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click.stop="handleQuotationSelect(row)">
                选择
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div v-else class="outsourcing-creation">
        <div class="quotation-info-bar">
          <span><strong>已选报价单：</strong>{{ selectedQuotation.quotationNo }} - {{ selectedQuotation.customerName }}</span>
          <el-button type="text" @click="resetSelection">重新选择</el-button>
        </div>

        <h4>第二步：选择物料和供应商</h4>
        <el-form
          ref="createFormRef"
          :model="createForm"
          :rules="createRules"
          label-width="120px"
          size="default"
        >
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="物料明细" prop="quotationItemId">
                <el-select
                  v-model="createForm.quotationItemId"
                  placeholder="请选择物料明细"
                  style="width: 100%"
                  @change="handleItemSelect"
                >
                  <el-option
                    v-for="item in selectedQuotation.items"
                    :key="item.id"
                    :label="`${item.productName} (${item.materialCode || '无编码'}) - 数量: ${item.quantity}`"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierCode">
                <el-select
                  v-model="createForm.supplierCode"
                  placeholder="请选择供应商"
                  style="width: 100%"
                  filterable
                  allow-create
                  @change="handleSupplierChange"
                >
                  <el-option
                    v-for="supplier in supplierOptions"
                    :key="supplier.supplierCode"
                    :label="`${supplier.supplierCode} - ${supplier.supplierName}`"
                    :value="supplier.supplierCode"
                  />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="供应商名称" prop="supplierName">
                <el-input
                  v-model="createForm.supplierName"
                  placeholder="请输入供应商名称"
                  @blur="handleSupplierNameChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品名称">
                <el-input
                  v-model="createForm.productName"
                  placeholder="自动填充"
                  readonly
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="外发数量" prop="quantity">
                <el-input
                  v-model.number="createForm.quantity"
                  placeholder="请输入外发数量"
                  style="width: 100%"
                  @input="handleQuantityInput"
                  @blur="calculateTotalAmount"
                >
                  <template #suffix>
                    <span style="color: #999;">PCS</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外发单价">
                <el-input
                  v-model.number="createForm.unitPrice"
                  placeholder="请输入外发单价"
                  style="width: 100%"
                  @input="handleUnitPriceInput"
                  @blur="calculateTotalAmount"
                >
                  <template #suffix>
                    <span style="color: #999;">元</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="外发总金额">
                <el-input
                  v-model.number="createForm.totalAmount"
                  placeholder="请输入外发总金额"
                  style="width: 100%"
                  @input="handleTotalAmountInput"
                >
                  <template #suffix>
                    <span style="color: #999;">元</span>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="外发日期" prop="outsourcingDate">
                <el-date-picker
                  v-model="createForm.outsourcingDate"
                  type="date"
                  placeholder="选择外发日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计回厂日期">
                <el-date-picker
                  v-model="createForm.expectedReturnDate"
                  type="date"
                  placeholder="选择预计回厂日期"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="备注">
            <el-input
              v-model="createForm.remark"
              type="textarea"
              :rows="3"
              placeholder="请输入备注信息"
            />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button v-if="selectedQuotation" type="primary" @click="handleCreate" :loading="createLoading">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 外发单详情对话框 -->
    <el-dialog
      v-model="showDetailDialog"
      title="外发单详情"
      width="800px"
    >
      <el-descriptions :column="2" border v-if="currentDetail">
        <el-descriptions-item label="外发单号">{{ currentDetail.outsourcingNo }}</el-descriptions-item>
        <el-descriptions-item label="报价单号">{{ currentDetail.quotationNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="供应商代码">{{ currentDetail.supplierCode }}</el-descriptions-item>
        <el-descriptions-item label="供应商名称">{{ currentDetail.supplierName }}</el-descriptions-item>
        <el-descriptions-item label="产品名称">{{ currentDetail.productName }}</el-descriptions-item>
        <el-descriptions-item label="物料编码">{{ currentDetail.materialCode || '-' }}</el-descriptions-item>
        <el-descriptions-item label="外发数量">{{ currentDetail.quantity }}</el-descriptions-item>
        <el-descriptions-item label="外发单价">{{ formatCurrency(currentDetail.unitPrice) }}</el-descriptions-item>
        <el-descriptions-item label="外发总金额">{{ formatCurrency(currentDetail.totalAmount) }}</el-descriptions-item>
        <el-descriptions-item label="外发日期">{{ currentDetail.outsourcingDate }}</el-descriptions-item>
        <el-descriptions-item label="预计回厂日期">{{ currentDetail.expectedReturnDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="实际回厂日期">{{ currentDetail.actualReturnDate || '-' }}</el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusTagType(currentDetail.status)">
            {{ currentDetail.status }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ currentDetail.createdBy || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createdAt) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updatedAt) }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentDetail.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="showStatusDialog"
      title="更新外发状态"
      width="500px"
    >
      <el-form
        ref="statusFormRef"
        :model="statusForm"
        :rules="statusRules"
        label-width="120px"
      >
        <el-form-item label="当前状态">
          <el-tag :type="getStatusTagType(statusForm.currentStatus)">
            {{ statusForm.currentStatus }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态" prop="status">
          <el-select
            v-model="statusForm.status"
            placeholder="请选择新状态"
            style="width: 100%"
          >
            <el-option label="已外发" value="已外发" />
            <el-option label="加工中" value="加工中" />
            <el-option label="已回厂" value="已回厂" />
            <el-option label="已取消" value="已取消" />
          </el-select>
        </el-form-item>
        <el-form-item label="实际回厂日期" v-if="statusForm.status === '已回厂'">
          <el-date-picker
            v-model="statusForm.actualReturnDate"
            type="date"
            placeholder="选择实际回厂日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showStatusDialog = false">取消</el-button>
        <el-button type="primary" @click="handleStatusUpdate" :loading="statusLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { outsourcingAPI, supplierAPI, quotationAPI } from '../utils/api.js'

// 响应式数据
const loading = ref(false)
const createLoading = ref(false)
const statusLoading = ref(false)
const quotationLoading = ref(false)
const tableData = ref([])
const supplierOptions = ref([])
const availableQuotations = ref([])
const selectedQuotation = ref(null)

// 对话框显示状态
const showCreateDialog = ref(false)
const showDetailDialog = ref(false)
const showStatusDialog = ref(false)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0
})

// 搜索表单
const searchForm = reactive({
  outsourcingNo: '',
  supplierCode: '',
  supplierName: '',
  productName: '',
  status: '',
  dateRange: [],
  quotationNo: ''
})

// 新增表单
const createForm = reactive({
  quotationId: null,
  quotationItemId: null,
  supplierCode: '',
  supplierName: '',
  materialCode: '',
  productName: '',
  quantity: 1,
  unitPrice: 0,
  totalAmount: 0,
  outsourcingDate: '',
  expectedReturnDate: '',
  remark: ''
})

// 新增表单验证规则
const createRules = {
  quotationItemId: [
    { required: true, message: '请选择物料明细', trigger: 'change' }
  ],
  supplierCode: [
    { required: true, message: '请选择或输入供应商代码', trigger: 'change' }
  ],
  supplierName: [
    { required: true, message: '请输入供应商名称', trigger: 'blur' }
  ],
  quantity: [
    { required: true, message: '请输入外发数量', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        const num = Number(value)
        if (!num || num <= 0 || !Number.isInteger(num)) {
          callback(new Error('外发数量必须为正整数'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  unitPrice: [
    { 
      validator: (rule, value, callback) => {
        if (value !== undefined && value !== null && value !== '') {
          const num = Number(value)
          if (isNaN(num) || num < 0) {
            callback(new Error('外发单价必须为非负数'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  outsourcingDate: [
    { required: true, message: '请选择外发日期', trigger: 'change' }
  ]
}

// 状态更新表单
const statusForm = reactive({
  id: null,
  currentStatus: '',
  status: '',
  actualReturnDate: ''
})

// 状态更新验证规则
const statusRules = {
  status: [
    { required: true, message: '请选择新状态', trigger: 'change' }
  ]
}

// 当前详情数据
const currentDetail = ref(null)

// 表单引用
const createFormRef = ref()
const statusFormRef = ref()

// 计算属性
const searchParams = computed(() => {
  const params = { ...searchForm }
  if (params.dateRange && params.dateRange.length === 2) {
    params.startDate = params.dateRange[0]
    params.endDate = params.dateRange[1]
  }
  delete params.dateRange
  return params
})

// 方法
const loadTableData = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      size: pagination.size,
      ...searchParams.value
    }
    
    const response = await outsourcingAPI.getOutsourcingPage(params)
    if (response.code === 200) {
      tableData.value = response.data.records
      pagination.total = response.data.total
    }
  } catch (error) {
    ElMessage.error('获取外发单列表失败')
  } finally {
    loading.value = false
  }
}

const loadSupplierOptions = async () => {
  try {
    const response = await supplierAPI.getAllSuppliers()
    if (response.code === 200) {
      supplierOptions.value = response.data
    }
  } catch (error) {
    console.error('获取供应商选项失败:', error)
  }
}

const loadAvailableQuotations = async () => {
  quotationLoading.value = true
  try {
    const response = await outsourcingAPI.getAvailableQuotationsForOutsourcing()
    if (response.code === 200) {
      availableQuotations.value = response.data
    }
  } catch (error) {
    console.error('获取可用报价记录失败:', error)
    ElMessage.error('获取可用报价记录失败')
  } finally {
    quotationLoading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadTableData()
}

const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    if (Array.isArray(searchForm[key])) {
      searchForm[key] = []
    } else {
      searchForm[key] = ''
    }
  })
  handleSearch()
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadTableData()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadTableData()
}

const handleSupplierChange = (supplierCode) => {
  const selectedSupplier = supplierOptions.value.find(s => s.supplierCode === supplierCode)
  if (selectedSupplier) {
    createForm.supplierName = selectedSupplier.supplierName
  }
}

const handleSupplierNameChange = (supplierName) => {
  const selectedSupplier = supplierOptions.value.find(s => s.supplierName === supplierName)
  if (selectedSupplier) {
    createForm.supplierCode = selectedSupplier.supplierCode
  }
}

const handleQuantityInput = () => {
  // 确保输入的是正整数
  if (createForm.quantity < 0) {
    createForm.quantity = 0
  }
  if (createForm.quantity && !Number.isInteger(Number(createForm.quantity))) {
    createForm.quantity = Math.floor(Number(createForm.quantity))
  }
  calculateTotalAmount()
}

const handleUnitPriceInput = () => {
  // 确保输入的是正数
  if (createForm.unitPrice < 0) {
    createForm.unitPrice = 0
  }
  calculateTotalAmount()
}

const handleTotalAmountInput = () => {
  // 确保输入的是正数
  if (createForm.totalAmount < 0) {
    createForm.totalAmount = 0
  }
}

const calculateTotalAmount = () => {
  // 自动计算总金额：数量 × 单价
  const quantity = Number(createForm.quantity) || 0
  const unitPrice = Number(createForm.unitPrice) || 0
  
  if (quantity > 0 && unitPrice > 0) {
    createForm.totalAmount = Math.round(quantity * unitPrice * 100) / 100  // 保留2位小数
  } else if (quantity === 0 || unitPrice === 0) {
    createForm.totalAmount = 0
  }
}

const handleCreate = async () => {
  try {
    await createFormRef.value.validate()
    createLoading.value = true
    
    // 准备提交数据，确保数字类型正确
    const submitData = {
      ...createForm,
      quantity: Number(createForm.quantity) || 0,
      unitPrice: Number(createForm.unitPrice) || 0,
      totalAmount: Number(createForm.totalAmount) || 0,
      createdBy: 'admin' // 实际应用中应该从用户信息获取
    }
    
    // 验证必要字段
    if (submitData.quantity <= 0) {
      ElMessage.error('外发数量必须大于0')
      return
    }
    
    const response = await outsourcingAPI.createOutsourcing(submitData)
    if (response.code === 200) {
      ElMessage.success('外发单创建成功')
      showCreateDialog.value = false
      resetCreateForm()
      loadTableData()
    }
  } catch (error) {
    if (error.message !== 'Validation failed') {
      console.error('创建外发单失败:', error)
      ElMessage.error('创建外发单失败：' + (error.response?.data?.message || error.message))
    }
  } finally {
    createLoading.value = false
  }
}

const resetCreateForm = () => {
  Object.keys(createForm).forEach(key => {
    if (typeof createForm[key] === 'number') {
      createForm[key] = key === 'quantity' ? 1 : 0
    } else {
      createForm[key] = ''
    }
  })
  createFormRef.value?.clearValidate()
}

const handleCreateDialogClose = () => {
  resetCreateForm()
  selectedQuotation.value = null
  showCreateDialog.value = false
}

const handleViewDetail = async (row) => {
  try {
    const response = await outsourcingAPI.getOutsourcingById(row.id)
    if (response.code === 200) {
      currentDetail.value = response.data
      showDetailDialog.value = true
    }
  } catch (error) {
    ElMessage.error('获取外发单详情失败')
  }
}

const handleUpdateStatus = (row) => {
  statusForm.id = row.id
  statusForm.currentStatus = row.status
  statusForm.status = ''
  statusForm.actualReturnDate = ''
  showStatusDialog.value = true
}

const handleStatusUpdate = async () => {
  try {
    await statusFormRef.value.validate()
    statusLoading.value = true
    
    const updateData = {
      status: statusForm.status
    }
    
    if (statusForm.status === '已回厂' && statusForm.actualReturnDate) {
      updateData.actualReturnDate = statusForm.actualReturnDate
    }
    
    const response = await outsourcingAPI.updateOutsourcingStatus(statusForm.id, updateData)
    if (response.code === 200) {
      ElMessage.success('状态更新成功')
      showStatusDialog.value = false
      loadTableData()
    }
  } catch (error) {
    if (error.message !== 'Validation failed') {
      ElMessage.error('状态更新失败')
    }
  } finally {
    statusLoading.value = false
  }
}

const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除外发单 "${row.outsourcingNo}" 吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await outsourcingAPI.deleteOutsourcing(row.id)
      if (response.code === 200) {
        ElMessage.success('外发单删除成功')
        loadTableData()
      }
    } catch (error) {
      ElMessage.error('删除外发单失败')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

const handleQuotationSelect = async (quotation) => {
  try {
    // 获取报价单详情（包含物料明细）
    const response = await quotationAPI.getQuotationById(quotation.id)
    if (response.code === 200) {
      selectedQuotation.value = response.data
      createForm.quotationId = quotation.id
      createForm.outsourcingDate = new Date().toISOString().split('T')[0] // 默认今天
    }
  } catch (error) {
    console.error('获取报价单详情失败:', error)
    ElMessage.error('获取报价单详情失败')
  }
}

const handleItemSelect = (itemId) => {
  if (!selectedQuotation.value || !selectedQuotation.value.items) return
  
  const selectedItem = selectedQuotation.value.items.find(item => item.id === itemId)
  if (selectedItem) {
    createForm.productName = selectedItem.productName || ''
    createForm.materialCode = selectedItem.materialCode || ''
    createForm.quantity = selectedItem.quantity || 1
    // 清空价格相关字段，需要手动输入
    createForm.unitPrice = 0
    createForm.totalAmount = 0
  }
}

const resetSelection = () => {
  selectedQuotation.value = null
  resetCreateForm()
}

const getQuotationStatusTagType = (status) => {
  const statusMap = {
    '草稿': 'info',
    '已提交': 'primary',
    '已生成合同': 'warning',
    '合同审核通过': 'success',
    '外发加工中': '',
    '已入库': 'success',
    '合同审核拒绝': 'danger'
  }
  return statusMap[status] || 'info'
}

const handleShowCreateDialog = async () => {
  showCreateDialog.value = true
  await loadAvailableQuotations()
  await loadSupplierOptions()
}

// 工具方法
const formatCurrency = (value) => {
  if (value == null || value === '') return '-'
  return `¥${Number(value).toFixed(2)}`
}

const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '-'
  return new Date(dateTimeStr).toLocaleString('zh-CN')
}

const getStatusTagType = (status) => {
  const statusMap = {
    '已外发': '',
    '加工中': 'warning',
    '已回厂': 'success',
    '已取消': 'danger'
  }
  return statusMap[status] || ''
}

// 生命周期
onMounted(() => {
  loadTableData()
})
</script>

<style scoped>
.outsourcing-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #303133;
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-dialog__body {
  padding: 10px 20px;
}

.el-descriptions {
  margin-top: 10px;
}

/* 新增外发单弹窗样式 */
.quotation-selection h4 {
  margin: 0 0 15px 0;
  color: #409eff;
  font-size: 16px;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.clickable-row {
  cursor: pointer;
}

.clickable-row:hover {
  background-color: #f5f7fa;
}

.quotation-info-bar {
  background: #f0f9ff;
  padding: 12px;
  border-radius: 4px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-left: 4px solid #409eff;
}

.outsourcing-creation h4 {
  margin: 0 0 15px 0;
  color: #67c23a;
  font-size: 16px;
  border-bottom: 2px solid #67c23a;
  padding-bottom: 8px;
}
</style> 